//****************************************//
//**Functions concerning user-accounts****//
//****************************************//
function logIn(event){
    var userName=$('email').value;
    var pass=$('password').value;
    $('errorLogin').update(createLoader('Logging in'));
    new Ajax.Request('Ajax.php',{
        method:'post',
        parameters:{login:userName,password:pass},
        onSuccess:logged
    });
}
function logged(data){
    var response=eval('(' + data.responseText + ')');
    if(response[0]=='error'){
        $('errorLogin').update(nl2br_js(response[1]));
    }
    else{
        var name=response[1];
        $('loggedIn').update('Welcome '+name+' <br/><a href="logout.php">Logout</a>');
        $('reg').remove();
        popup('loginDiv');
        setPlaylistNamesR(null);
        $('errorLogin').update();
    }
}
function isLoggedInR(){
    new Ajax.Request(ajaxFile,{
        method:'post',
        parameters:{loggedIn:'1'},
        onSuccess:isLoggedIn
    });
}
function isLoggedIn(data){
    var response=eval('(' + data.responseText + ')');
    if(response[0]==true){
        $('loggedIn').update('Welcome '+response[1]+' <br/><a href="logout.php">Logout</a>');
        $('reg').remove();
    }
}
//****************************************//
//****Processes search********************//
//****************************************//
function searchTrackForArtist(event){
    addLoading('searching songs');
    //Ajax call to request the song
    new Ajax.Request(ajaxFile,{
        method:'post',
        parameters:{searchTerm:this.artistName},
        onSuccess:addSongsToResult
    });
}
function searchSong(event){
    var search=$('searchbar').value;
    addLoading('searching songs');
    //Ajax call to request the song
    new Ajax.Request(ajaxFile,{
        method:'post',
        parameters:{searchTerm:search},
        onSuccess:addSongsToResult
    });
}
function addSongsToResult(data){
    removeLoading('searching songs');
    //eval data
    var response=eval('('+data.responseText+')');
    //loop through all elements

    if(response[0]==null){
        switchMiddle('results');
        $('resultResults').update('No results found.');
        $('resultPlaylists').update('No suggested playlists found.');
    }
    else{
        var artistNames=''; //after the loop is should look like this: Jedi Mind Tricks;Ill Bill;
        var ulTrack=new Element('ul');
        for(var i=0;i<response.length;i++){
            var artist=response[i];
            artistNames+=artist.name+';';

            var tracks=artist.search;
            
            

            for(var j=0;j<tracks.length;j++){
                var track=tracks[j];
                var li=new Element('li',{'class':'liTrack'});

                var spanArtist=new Element('span',{'class':'link'});
                var textElement=new Element('sp',{'title':'Show artist info'}).update(artist.name);
                textElement.artistName=artist.name;
                textElement.artistID=artist.id;
                textElement.observe('click',showArtistInfoR);


                var imgPlay=new Element('img',{'src':'playIcon.png','title':'Play this track'});
                imgPlay.trackID=track.id;
                imgPlay.trackName=track.name;
                imgPlay.artistID=artist.id;
                imgPlay.artistName=artist.name;
                imgPlay.observe('click',_track);

                var expand=new Element('img',{'src':'expand-icon-plus.gif','title':'Add to playlist'});
                expand.trackID=track.id;
                expand.trackName=track.name;
                expand.artistID=artist.id;
                expand.artistName=artist.name;
                expand.observe('click',popupPlaylist);

                var span=new Element('span',{'class':'link','title':'Play this track'});
                span.update(track.name);
                span.trackID=track.id;
                span.trackName=track.name;
                span.artistID=artist.id;
                span.artistName=artist.name;
                span.observe('click',_track);

                spanArtist.insert(imgPlay);
                spanArtist.insert(textElement);
                //liTrack.insert(expand); this item doesn't contain the album id so we can't add this to a playlist

                li.insert(spanArtist);
                li.insert(span);
                ulTrack.insert(li);
            }

            
        }
        $('resultResults').update(ulTrack);
        switchMiddle('results');
        addLoading('loading suggested playlists');
        //call suggested playlist
        new Ajax.Request(ajaxFile,{
            method:'post',
            parameters:{getTopPlaylists:artistNames},
            onSuccess:addPlaylistsToResult
        });
    }
}
function addPlaylistsToResult(data){
    removeLoading('loading suggested playlists');
    //eval data
    var response=eval('('+data.responseText+')');
    response=response[0];
    if(response[0]==null){
        switchMiddle('results');
        $('resultPlaylists').update('No suggested playlists found.');
    }
    else{
        $('resultPlaylists').update();
        for(var i=0;i<response.length;i++){

            var outerDiv=new Element('div',{'class':'playlist'});

            var title=new Element('h3');
            title.update(response[i].name);

            var innerDiv=new Element('div',{'class':'playlistList'});

            var ul=new Element('ul');

            var hideCount=3;
            for(var j=0;j<response[i].tracks.length;j++){

                var li=new Element('li',{'class':'liTrack'});
                if(j>hideCount){
                    li.addClassName('hide');
                }

                var imgPlay=new Element('img',{'src':'playIcon.png','title':'Play this track'});
                imgPlay.trackID=response[i].tracks[j].id;
                imgPlay.trackName=response[i].tracks[j].name;
                imgPlay.artistID=response[i].artists[j].id;
                imgPlay.artistName=response[i].artists[j].name;
                imgPlay.albumID=response[i].albums[j].id;
                imgPlay.albumName=response[i].albums[j].name;
                imgPlay.observe('click',_track);

                var expand=new Element('img',{'src':'expand-icon-plus.gif','title':'Add to playlist'});
                expand.trackID=response[i].tracks[j].id;
                expand.trackName=response[i].tracks[j].name;
                expand.artistID=response[i].artists[j].id;
                expand.artistName=response[i].artists[j].name;
                expand.albumID=response[i].albums[j].id;
                expand.albumName=response[i].albums[j].name;
                expand.observe('click',popupPlaylist);

                var span=new Element('span',{'class':'link','title':'Play this track'});
                span.update(response[i].tracks[j].name);
                span.trackID=response[i].tracks[j].id;
                span.trackName=response[i].tracks[j].name;
                span.artistID=response[i].artists[j].id;
                span.artistName=response[i].artists[j].name;
                span.albumID=response[i].albums[j].id;
                span.albumName=response[i].albums[j].name;
                span.observe('click',_track);

                li.insert(imgPlay);li.insert(expand);li.insert(span);
                ul.insert(li);
            }
            var expandDiv=new Element('div',{'class':'expand','title':'expand/collaps'});
            expandDiv.observe('click',_expand);

            var hr=new Element('hr');

            innerDiv.insert(ul);
            outerDiv.insert(title);outerDiv.insert(innerDiv);outerDiv.insert(expandDiv);outerDiv.insert(hr);
            $('resultPlaylists').insert(outerDiv);
        }
    }
    switchMiddle('results');
}
//************************************//
//functions for artist info, albums***//
//************************************//
function showArtistInfoR(event){
    addLoading('loading artist info');
    addLoading('loading artist albums');
    var element=this;
    //argument should be an element, with artistID
    var artistID=element.artistID;
    var artistName=element.artistName;
    //request avatar, bio
    new Ajax.Request(ajaxFile,{
        method:'post',
        parameters:{getArtistInfo:artistName},
        onSuccess:showArtistInfo
    });
    new Ajax.Request(ajaxFile,{
       method:'post',
       parameters:{getAllAlbumsOfArtist:artistID},
       onSuccess:showArtistAlbums
    });
    }
    function showArtistInfo(data){
    removeLoading('loading artist info');
    //eval data
    var response=eval('('+data.responseText+')');

    var avatar=response[0];
    var bio=nl2br_js(response[1]);

    $('artistAvatar').setAttribute('src',avatar);
    bio=addExpandCollaps(bio);

    $('artistBio').update(bio);

    switchMiddle('artist');
}
function showArtistAlbumsR(event){
    addLoading('loading artist albums');
    var element=this;
    //argument should be an element, with artistID
    var artistID=element.artistID;
    //request all albums
    new Ajax.Request(ajaxFile,{
       method:'post',
       parameters:{getAllAlbumsOfArtist:artistID},
       onSuccess:showArtistAlbums
    });
}
function showArtistAlbums(data){
    removeLoading('loading artist albums');
    //eval data
    var response=eval('('+data.responseText+')');
    var albums=response.albums;
    $('albumsContent').update();
    for(var i=0;i<albums.length;i++){
       var outerDiv=new Element('div',{'class':'albumsItem'});
       var title=new Element('h3').update(albums[i].name);

       var albumLeft=new Element('div',{'class':'albumLeft'});
       var imgAlbum=new Element('img',{'src':albums[i].cover,'class':'avatar'});
       var showAlbum=new Element('span',{'class':'link'}).update('Show info');
       showAlbum.artistID=response.id;
       showAlbum.artistName=response.name;
       showAlbum.albumID=albums[i].id;
       showAlbum.albumName=albums[i].name;
       showAlbum.observe('click',showAlbumInfoR);

       var playlist=new Element('div',{'class':'playlistList'});
       var ul=new Element('ul');
       for(var j=0;j<albums[i].tracks.length;j++){
            var li=new Element('li',{'class':'liTrack'});

            var imgPlay=new Element('img',{'src':'playIcon.png','title':'Play this track'});
            imgPlay.trackID=albums[i].tracks[j].id;
            imgPlay.trackName=albums[i].tracks[j].name;
            imgPlay.artistID=response.id;
            imgPlay.artistName=response.name;
            imgPlay.albumID=albums[i].id;
            imgPlay.albumName=albums[i].name;
            imgPlay.observe('click',_track);

            var expand=new Element('img',{'src':'expand-icon-plus.gif','title':'Add to playlist'});
            expand.trackID=albums[i].tracks[j].id;
            expand.trackName=albums[i].tracks[j].name;
            expand.artistID=response.id;
            expand.artistName=response.name;
            expand.albumID=albums[i].id;
            expand.albumName=albums[i].name;
            expand.observe('click',popupPlaylist);

            var span=new Element('span',{'class':'link','title':'Play this track'});
            span.trackID=albums[i].tracks[j].id;
            span.trackName=albums[i].tracks[j].name;
            span.artistID=response.id;
            span.artistName=response.name;
            span.albumID=albums[i].id;
            span.albumName=albums[i].name;
            span.update(albums[i].tracks[j].name);
            span.observe('click',_track);

            li.insert(imgPlay);li.insert(expand);li.insert(span);
            ul.insert(li);
        }
        playlist.insert(ul);
        albumLeft.insert(imgAlbum);albumLeft.insert(showAlbum);

       var hr=new Element('hr');
       outerDiv.insert(title);outerDiv.insert(albumLeft);outerDiv.insert(playlist);outerDiv.insert(hr);
       $('albumsContent').insert(outerDiv);
    }

}
//************************************//
//functions for album info, tracks****//
//************************************//
function showAlbumInfoR(event){
    addLoading('loading album info');
    //element should have artistID, albumID
    
    var albumID=this.albumID;
    //Request all tracks, image and info of the album
    new Ajax.Request(ajaxFile,{
        method:'post',
        parameters:{getFullAlbum:albumID,artistID:this.artistID},
        onSuccess:showAlbumInfo
    });
}
function showAlbumInfo(data){
    removeLoading('loading album info');
    //eval data
    var response=eval('('+data.responseText+')');
    var album=response[0];
    $('albumAvatar').setAttribute('src',response[0].cover);
    var bio=nl2br_js(response[0].info);
    bio=addExpandCollaps(bio);
    $('albumInfo').update(bio);
    var tracks=response[0].tracks;
    var ul=new Element('ul');
    for(var i=0;i<tracks.length;i++){
        var li=new Element('li',{'class':'liTrack'});

        var imgPlay=new Element('img',{'src':'playIcon.png','title':'Play'});
        imgPlay.trackID=tracks[i].id;
        imgPlay.trackName=tracks[i].name;
        imgPlay.artistID=response[1].id;
        imgPlay.artistName=response[1].name;
        imgPlay.albumID=album.id;
        imgPlay.albumName=album.name;
        imgPlay.observe('click',_track);

        var expand=new Element('img',{'src':'expand-icon-plus.gif','title':'Add to playlist'});
        expand.trackID=tracks[i].id;
        expand.trackName=tracks[i].name;
        expand.artistID=response[1].id;
        expand.artistName=response[1].name;
        expand.albumID=album.id;
        expand.albumName=album.name;
        expand.observe('click',popupPlaylist);

        var span=new Element('span',{'class':'link','title':'Play this track'});
        span.trackID=tracks[i].id;
        span.trackName=tracks[i].name;
        span.artistID=response[1].id;
        span.artistName=response[1].name;
        span.albumID=album.id;
        span.albumName=album.name;
        span.update(tracks[i].name);
        span.observe('click',_track);

        li.insert(imgPlay);li.insert(expand);li.insert(span);
        ul.insert(li);
    }
    $('albumTracks').update(ul);
    switchMiddle('album');
}
//************************************//
//functions concerning tracks********//
//************************************//
function vote(stars){
    addLoading('processing vote');
    //25px == 1 star
    $('current-rating').setStyle({'width':stars*25+'px'});
    //the element with id currentTrack should contain the track id, artist id and album id
    var trackID=$('currentTrack').trackID;
    //make ajax call
    new Ajax.Request(ajaxFile,{
        method:'post',
        parameters:{rating:stars,rate:trackID},
        onSuccess:function(data){removeLoading('processing vote');}
    });
    }
    function setRating(data){
    var response=data.responseText;
    $('stars').setStyle({'display':'block'});
    $('current-rating').setStyle({'width':(response*25)+'px'});
}
function next(){
    //the element with id currentNext should contain the track id, artist id and album id, with their names
    if($('currentNext').trackID){
        _track($('currentNext'));
    }
}
function _play(data){
    removeLoading('loading track');
    //eval data
    var link=data.responseText;
    updateLink(link);
    switchMiddle('track');
    new Ajax.Request(ajaxFile,{
        method:'post',
        parameters:{listening:$('currentTrack').trackID,artist:$('currentTrack').artistID}
    });
}

/**
*this function is called when someone clicked on the track
*/
function _track(element){
    //check if this track is in the current play list, if no, set currentPlaylist to none, if yes ask ajax what the next song is going to be and call nextSet
    //ask ajax for youtube link and call _play
    //set currentTrack to this
    //set currentArtist to the artist of this track
    //set currentAlbum to the album of this track
    var track;
    if(element.trackID){
        track=element;
    }
    else{
        track=this;
    }
    var artistID=track.artistID;
    var artistName=track.artistName;
    var albumName=null;
    var albumID=null;
    if(track.albumName){
        albumName=track.albumName;
        albumID=track.albumID;
    }
    var trackID=track.trackID;
    var trackName=track.trackName;

    $('currentArtist').update(artistName);
    $('currentArtist').observe('click',showArtistInfoR);
    $('currentArtist').artistID=artistID;
    $('currentArtist').artistName=artistName;

    if(albumName){
    $('currentAlbum').update(albumName);
    $('currentAlbum').observe('click',showAlbumInfoR);
    }
    else{
        $('currentAlbum').update('<i>Unknown album</i>');
    }
    $('currentAlbum').albumName=albumName;
    $('currentAlbum').albumID=albumID;
    $('currentAlbum').artistID=artistID;
    $('currentAlbum').artistName=artistName;

    $('currentTrack').albumName=albumName;
    $('currentTrack').albumID=albumID;
    $('currentTrack').artistID=artistID;
    $('currentTrack').artistName=artistName;
    $('currentTrack').update(trackName);
    $('currentTrack').trackID=trackID;
    $('currentTrack').trackName=trackName;
    $('currentTrack').observe('click',function(){switchMiddle('track')});

    //remove current video
    //$('ytplayer').update();
    //clear rating
    $('stars').setStyle({'display':'none'});
    $('current-rating').setStyle({'width':'0px'});
    //make ajax requests
    addLoading('loading track');
    new Ajax.Request(ajaxFile,{
        method:'post',
        parameters:{youtubeGetArtist:artistName,trackName:trackName},
        onSuccess:_play
    });
    new Ajax.Request(ajaxFile,{
        method:'post',
        parameters:{getRating:trackID},
        onSuccess:setRating
    });
    //set next track
    var current=null;

    if(currentPlaylistObj){
        //loop through obj and get the next song
        for(var i=0;i<currentPlaylistObj.length;i++){

            if(currentPlaylistObj[i].trackID==trackID){
                current=null;
                if(i+1==currentPlaylistObj.length){
                    current=currentPlaylistObj[0];
                }
                else{
                    current=currentPlaylistObj[i+1]
                }
                $('currentNext').trackID=current.trackID;
                $('currentNext').trackName=current.trackName;

                $('currentNext').albumID=current.albumID;
                $('currentNext').albumName=current.albumName;

                $('currentNext').artistID=current.artistID;
                $('currentNext').artistName=current.artistName;
                $('currentNext').observe('click',_play);

                $('currentNext').update(current.trackName);
                break;
            }
        }

     }
     //if current is null that means the user clicked on a track that wasn't in the playlist,
    //so set the new play list
    if(current==null){
        //2 options
        //track is descendent of playlist, that playlist will become current playlist
        if(track.playlistID){
            new Ajax.Request(ajaxFile,{
                method:'post',
                parameters:{getPlaylistByID:track.playlistID},
                onSuccess:setCurrentPlaylist
            });
        }
        //track is descendent of album(s), that album will become the current playlist
        else if(track.descendantOf('albums')||track.descendantOf('album')||track.descendantOf('resultPlaylists')){
            new Ajax.Request(ajaxFile,{
                method:'post',
                parameters:{albumPlaylist:track.albumID,artistID:track.artistID},
                onSuccess:setCurrentPlaylist
            });
        }
        else{
            currentPlaylistObj=null;
        }
    }   
}
//************************************//
//functions concerning recommendations//
//************************************//
function showRecommendationR(event){
    var artistID=$('currentTrack').artistID;
    if(artistID){
        addLoading('Calculating suggestions');
        new Ajax.Request(ajaxFile,{
            method:'post',
            parameters:{suggestion:artistID},
            onSuccess:showRecommendation
        });
    }
    else{
        $('recommendationList').update('<i>You must play a track to get suggestions</i>');
        $('recArtists').update('<i>You must play a track to get suggestions</i>');
        switchMiddle('recommendation');
    }
}
function showRecommendation(data){
    removeLoading('Calculating suggestions');
    var response=eval('('+data.responseText+')');
    var div=new Element('div',{'class':'playList'});
    var ul=new Element('ul');
    var ulArtists=new Element('ul');
    for(var i=0;i<response.length;i++){
        var artist=response[i];
        if(artist.albums.length==0){
            var li=new Element('li',{'class':'liTrack link','title':'Search for his/her songs'}).update(artist.name);
            li.setStyle({'padding-left':'10px'});
           
            li.artistID=artist.id;
            li.artistName=artist.name;
            li.observe('click',searchTrackForArtist);
            ulArtists.insert(li);
        }
        for(var j=0;j<artist.albums.length;j++){
            var album=artist.albums[j];
            for(var k=0;k<album.tracks.length;k++){
                var track= album.tracks[k];
                var li=new Element('li',{'class':'liTrack'});
                var spanArtist=new Element('span',{'class':'link'});
                var spanTrack=new Element('span',{'class':'link','title':'Play this track'}).update(track.name);
                var imgPlay=new Element('img',{'src':'playIcon.png','title':'Play this track'});
                var imgAdd=new Element('img',{'src':'expand-icon-plus.gif','title':'Add to playlist'});
                var nameArtist=new Element('sp').update(artist.name);
                
                imgPlay.artistID=nameArtist.artistID=spanTrack.artistID=imgAdd.artistID=artist.id;
                imgPlay.artistName=nameArtist.artistName=spanTrack.artistName=imgAdd.artistName=artist.name;
                imgPlay.albumID=spanTrack.albumID=imgAdd.albumID=album.id;
                imgPlay.albumName=spanTrack.albumName=imgAdd.albumName=album.name;
                imgPlay.trackID=spanTrack.trackID=imgAdd.trackID=track.id;
                imgPlay.trackName=spanTrack.trackName=imgAdd.trackName=track.name;
                imgPlay.onlick=spanTrack.onclick=_track;
                nameArtist.observe('click',showArtistInfoR);
                imgAdd.onclick=popupPlaylist;
                spanArtist.insert(imgPlay);spanArtist.insert(imgAdd);spanArtist.insert(nameArtist);
                li.insert(spanArtist);li.insert(spanTrack);
                ul.insert(li);
            }
        }   
    }
    div.insert(ul);
    $('recommendationList').update(div);
    $('recArtists').update(ulArtists);
    switchMiddle('recommendation');
}
//************************************//
//functions conerning playlist//
//************************************//
function setPlaylistNamesR(event){
    new Ajax.Request(ajaxFile,{
        method:'post',
        parameters:{getPlaylistNames:'1'},
        onSuccess:setPlaylistNames
    });
}
function setPlaylistNames(data){
    $('selectSPlaylist').update();
    var response=eval('('+data.responseText+')');

    for(var i=0;i<response.length;i++){

        var option=new Element('option').update(response[i].name);
        option.playlistID=response[i].id;
        option.playlistName=response[i].name;
        option.observe('click',addTrack);
        $('selectSPlaylist').insert(option);
    }
    }
    function removeTrack(element){
    //element should be the element that has to be removed, with a track id
    //loop through all elements, fetch their id, concat them like this: 23;44;1;133
    //give ajax the playlist that has been edited with the founded string (rule above ^)
    //remove the element
    this.ancestors()[0].remove();
}
function addTrack(event){

    if($('selectNamePlaylist').value.length>0){
        var name=$('selectNamePlaylist').value;
        var tracks=$('selectPlaylist').trackID;
        new Ajax.Request(ajaxFile,{
            method:'post',
            parameters:{savePlaylist:tracks,namePlaylist:name},
            onSuccess:setPlaylistNamesR
        });
        $('selectNamePlaylist').value='';
    }
    else{
        var elements=$$('#selectSPlaylist option');

        var id=-1;
        for(var i=0;i<elements.length;i++){
            if(elements[i].selected){
                id=elements[i].playlistID;
            }
        }
        if(id!=-1){
           if(currentPlaylistObj){
                if(id==currentPlaylistObj.playlistID){
                    var track=new Object;
                    track.trackID=$('selectPlaylist').trackID;
                    track.trackName=$('selectPlaylist').trackName;
                    track.albumName=$('selectPlaylist').albumName
                    track.albumID=$('selectPlaylist').albumID
                    track.artistID=$('selectPlaylist').artistID
                    track.artistName=$('selectPlaylist').artistName
                    currentPlaylistObj.push(track);
                }
            }
            
            new Ajax.Request(ajaxFile,{
                method:'post',
                parameters:{savePlaylist:id,trackID:$('selectPlaylist').trackID},
                onSuccess:setPlaylistNamesR
            });
        }
    }
    popup('selectPlaylist');
}
function showPlaylistsR(){
    addLoading('loading playlists');
    //ask ajax for all the playlists
    new Ajax.Request(ajaxFile,{method:'post',parameters:{getAllPlaylists:'1'},onSuccess:showPlaylists});
}
function showPlaylists(data){
    removeLoading('loading playlists');
    //eval data
    var response=eval('('+data.responseText+')');
    $('playlistRTY').update();
    if(response[0]==null){
        $('playlistRTY').update('No playlists found, you either have no playlists or you are not logged in.');
    }
    for(var i=0;i<response.length;i++){

        var outerDiv=new Element('div',{'class':'playlist'});

        var title=new Element('h3');
        title.update(response[i].name);

        var innerDiv=new Element('div',{'class':'playlistList'});

        var ul=new Element('ul');

        var hideCount=3;
        for(var j=0;j<response[i].tracks.length;j++){

            var li=new Element('li',{'class':'liTrack'});
            if(j>hideCount){
                li.addClassName('hide');
            }

            var imgPlay=new Element('img',{'src':'playIcon.png','title':'Play this track'});
            imgPlay.trackID=response[i].tracks[j].id;
            imgPlay.trackName=response[i].tracks[j].name;
            imgPlay.artistID=response[i].artists[j].id;
            imgPlay.artistName=response[i].artists[j].name;
            imgPlay.albumID=response[i].albums[j].id;
            imgPlay.albumName=response[i].albums[j].name;
            imgPlay.playlistID=response[i].id;
            imgPlay.observe('click',_track);

            var expand=new Element('img',{'src':'expand-icon-minus.gif','title':'Remove this track'});
            expand.trackID=response[i].tracks[j].id;
            expand.trackName=response[i].tracks[j].name;
            expand.artistID=response[i].artists[j].id;
            expand.artistName=response[i].artists[j].name;
            expand.albumID=response[i].albums[j].id;
            expand.albumName=response[i].albums[j].name;
            expand.playlistID=response[i].id;
            expand.observe('click',removeTrack);

            var span=new Element('span',{'class':'link','title':'Play this track'});
            span.update(response[i].tracks[j].name);
            span.trackID=response[i].tracks[j].id;
            span.trackName=response[i].tracks[j].name;
            span.artistID=response[i].artists[j].id;
            span.artistName=response[i].artists[j].name;
            span.albumID=response[i].albums[j].id;
            span.albumName=response[i].albums[j].name;
            span.playlistID=response[i].id;
            span.observe('click',_track);

            li.insert(imgPlay);li.insert(expand);li.insert(span);
            ul.insert(li);
        }
        var expandDiv=new Element('div',{'class':'expand','title':'expand/collaps'});
        expandDiv.observe('click',_expand);

        var hr=new Element('hr');

        innerDiv.insert(ul);
        outerDiv.insert(title);outerDiv.insert(innerDiv);outerDiv.insert(expandDiv);outerDiv.insert(hr);
        
    }
$('playlistRTY').insert(outerDiv);
    switchMiddle('playlists');
}
function setCurrentPlaylist(data){

    var response=eval('('+data.responseText+')');

    currentPlaylistObj=new Array;
    if(response.id){
        currentPlaylistObj.playlistID=response.id;
    }
    var outerDiv=new Element('div',{'class':'playlist'});
    var title=new Element('h3');
    title.update(response.name);
    var innerDiv=new Element('div',{'class':'playlistList'});
    var ul=new Element('ul');

    for(var i=0;i<response.tracks.length;i++){  
        var track=new Object();
        track.trackID=response.tracks[i].id;
        track.trackName=response.tracks[i].name;
        track.albumID=response.albums[i].name;
        track.albumName=response.albums[i].id;
        track.artistID=response.artists[i].id;
        track.artistName=response.artists[i].name;

        currentPlaylistObj.push(track);

        var li=new Element('li',{'class':'liTrack'});

        var imgPlay=new Element('img',{'src':'playIcon.png','title':'Play'});
        imgPlay.trackID=response.tracks[i].id;
        imgPlay.trackName=response.tracks[i].name;
        imgPlay.artistID=response.artists[i].id;
        imgPlay.artistName=response.artists[i].name;
        imgPlay.albumID=response.albums[i].id;
        imgPlay.albumName=response.albums[i].name;
        imgPlay.observe('click',_track);

        var expand=new Element('img',{'src':'expand-icon-minus.gif','title':'Remove this track'});
        expand.trackID=response.tracks[i].id;
        expand.trackName=response.tracks[i].name;
        expand.artistID=response.artists[i].id;
        expand.artistName=response.artists[i].name;
        expand.albumID=response.albums[i].id;
        expand.albumName=response.albums[i].name;
        expand.observe('click',removeTrack);

        var span=new Element('span',{'class':'link','title':'Play this track'});
        span.update(response.tracks[i].name);
        span.trackID=response.tracks[i].id;
        span.trackName=response.tracks[i].name;
        span.artistID=response.artists[i].id;
        span.artistName=response.artists[i].name;
        span.albumID=response.albums[i].id;
        span.albumName=response.albums[i].name;
        span.observe('click',_track);

        li.insert(imgPlay);li.insert(expand);li.insert(span);
        ul.insert(li);

        if($('currentTrack').trackID==response.tracks[i].id){
            var j=i+1;
            if(i+1==response.tracks.length){
                j=0;
            }

            $('currentNext').trackID=response.tracks[j].id;
            $('currentNext').trackName=response.tracks[j].name;

            $('currentNext').albumID=response.albums[j].id;
            $('currentNext').albumName=response.albums[j].name;

            $('currentNext').artistID=response.artists[j].id;
            $('currentNext').artistName=response.artists[j].name;
            $('currentNext').update(response.tracks[j].name);
            $('currentNext').observe('click',_track);

        }
    }

    innerDiv.insert(ul);
    outerDiv.insert(title);outerDiv.insert(innerDiv);
    $('trackPlaylist').update(outerDiv);
    $('currentPlaylist').update(response.name);

}
//************************************//
//statistics//
//************************************//
function showStatisticsR(){
    addLoading('loading statistics');
    //ask ajax for global and user statistics
    new Ajax.Request(ajaxFile,{
        method:'post',
        parameters:{statistics:'1'},
        onSuccess:showStatistics
    });
    //ask ajax for top 10 tracks of this user
    showTopTracks(null);
 }
 function showStatistics(data){
    removeLoading('loading statistics');
    //eval data
    var response=eval('('+data.responseText+')');
    //global
    var global=response.global;
    var ulGenre=new Element('ul',{'class':'genres'});
    var ulstat=new Element('ul',{'class':'statBar'});
    var largG=global[0].count;

    for(var i=0;i<global.length;i++){
        var liGenre=new Element('li').update(global[i].label);
        var liStat=new Element('li').update(global[i].count);
        var widthN=(global[i].count/largG)*400;
        liStat.setStyle({width:widthN+'px'});
        ulGenre.insert(liGenre);
        ulstat.insert(liStat);
    }
    $('globalStat').update(ulGenre);
    $('globalStat').insert(ulstat);
    //personal
    if(response.personal!='error'){
        var personal=response.personal;
        ulGenre=new Element('ul',{'class':'genres'});
        ulstat=new Element('ul',{'class':'statBar'});
        largG=personal[0].count;

        for(var i=0;i<personal.length;i++){
            var liGenre=new Element('li').update(personal[i].label);
            var liStat=new Element('li').update(personal[i].count);
            var widthN=(personal[i].count/largG)*400;
            liStat.setStyle({width:widthN+'px'});
            ulGenre.insert(liGenre);
            ulstat.insert(liStat);
        }
        $('userStat').update(ulGenre);
        $('userStat').insert(ulstat);
    }
    else{
        $('userStat').update('<i>There are no statistics for you.</i>');
    }
    switchMiddle('statistics');
}
function showTopTracks(data){
    //eval data,
    //dont switch to statistcs!
}
//************************************//
//Switches, collaps, show functions   //
//************************************//
function switchMiddle(show){
    var elements=$$('#middle .wrapper');
    for(var i=0;i<elements.length;i++){
        if(elements[i].hasClassName('show')){
            elements[i].removeClassName('show');
            elements[i].addClassName('hide');
        }
        if(elements[i].id==show){
            elements[i].addClassName('show');
            elements[i].removeClassName('hide');
        }
    }
}
function switchStat(element){

    if(element.hasClassName('link')){
        if(element.innerHTML=='Global'){
            element.toggleClassName('focus');

            $('globalStat').removeClassName('hide');
            $('globalStat').addClassName('show');
            $('statisticsInfoG').removeClassName('hide');
            $('statisticsInfoG').addClassName('show');

            $('userStat').removeClassName('show');
            $('userStat').addClassName('hide');
            $('statisticsInfoU').removeClassName('show');
            $('statisticsInfoU').addClassName('hide');

            element.next().addClassName('link');
            element.next().removeClassName('focus');
        }
        else{
            element.toggleClassName('focus');
            $('globalStat').removeClassName('show');
            $('globalStat').addClassName('hide');
            $('statisticsInfoG').removeClassName('show');
            $('statisticsInfoG').addClassName('hide');

            $('userStat').removeClassName('hide');
            $('userStat').addClassName('show');
            $('statisticsInfoU').removeClassName('hide');
            $('statisticsInfoU').addClassName('show');
            element.previous().addClassName('link');
            element.previous().removeClassName('focus');

        }
    }
}

function switchAlbumView(element){

    if(element.hasClassName('link')){
        if(element.innerHTML=='Show info'){
            element.toggleClassName('focus');
            $('albumInfo').removeClassName('hide');
            $('albumInfo').addClassName('show');
            $('albumTracks').removeClassName('show');
            $('albumTracks').addClassName('hide');
            element.next().next().addClassName('link');
            element.next().next().removeClassName('focus');
        }
        else{
            element.toggleClassName('focus');
            $('albumInfo').removeClassName('show');
            $('albumInfo').addClassName('hide');
            $('albumTracks').removeClassName('hide');
            $('albumTracks').addClassName('show');
            element.previous().previous().addClassName('link');
            element.previous().previous().removeClassName('focus');
        }
    }
}
function collapsText(element){
    element.removeClassName('show');
    element.addClassName('hide');

    element.previous().removeClassName('show');
    element.previous().addClassName('hide');
    element.previous().previous().removeClassName('hide');
    element.previous().previous().addClassName('show');
}
function showText(element){
    element.removeClassName('show');
    element.addClassName('hide');

    element.next().removeClassName('hide');
    element.next().addClassName('show');

    element.next().next().removeClassName('hide');
    element.next().next().addClassName('show');
}
function _expand(event){
    var element=this;
    var elements=element.parentNode.descendants();
    var show=false;
    for(var i=0;i<elements.length;i++){
        if(elements[i].hasClassName('hide')){
            show=true;
        }
    }
    for(var i=0;i<elements.length;i++){

        if(show && elements[i].hasClassName('hide')){
            elements[i].removeClassName('hide');
            elements[i].addClassName('show');
        }
        if(!show && elements[i].hasClassName('show')){
            elements[i].removeClassName('show');
            elements[i].addClassName('hide');
        }
    }
    element.toggleClassName('collaps');
}
//**********************************//
//****Youtube functions*************//
//**********************************//
function updateLink(youtubeID){
    if(player){
        console.log(youtubeID);
        player.loadVideoById(youtubeID);
    }
    else{
        var tag = document.createElement('script');
        tag.src = "http://www.youtube.com/player_api";
        var firstScriptTag = document.getElementsByTagName('script')[0];
        firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
        $('ytplayer').youtubeID=youtubeID;
    }
    }

    var player;
    function onYouTubePlayerAPIReady() {
    player = new YT.Player('ytplayer', {
       width:'550',
       height:'290',
      videoId: $('ytplayer').youtubeID,
       playerVars : {wmode:'opaque',showinfo:0},
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }
    });
}

function onPlayerReady(event) {
    event.target.playVideo();
}

function onPlayerStateChange(event) {
    if(event.data==0){
        next();
    }
}

//*************************************//
//creates loader//
//*************************************//
function addLoading(text){
    var li=new Element('li',{'class':'loading'});
    li.setStyle({'display':'none'});
    var picNode=new Element('img',{'src':'ajax-loader.gif'});
    li.update(text);
    li.insert(picNode);
    $('loadingUL').insert(li);
    li.appear();
    }
    function removeLoading(text){
    var nodes=$$('#loadingUL li');

    for(var i=0;i<nodes.length;i++){
        if(nodes[i].childNodes[0].wholeText==text){
            nodes[i].fade();
        }
    }

}
function createLoader(text){
    var node=new Element('span');
    node.addClassName('loading');
    var textNode=new Element('span');
    textNode.update(text);
    var picNode=new Element('img');
    picNode.setAttribute('src', 'ajax-loader.gif');
    node.insert(textNode);
    node.insert(picNode);
    return node;
}
//*************************************//
//Additional functions//
//*************************************//
function addExpandCollaps(text){

    if(text.length>777){
        var firstPart=text.substring(0,777);

        var secondPart=text.substring(777,text.length-1);

        firstPart+='<span class="link" onclick="showText(this)">....Show more</span> <div class="hide">';
        secondPart+='</div><span class="link hide" onclick="collapsText(this)"><br/>Collaps</span>';
        text=firstPart+secondPart;
        return text;
    }
    return text;
}
function shortText(text,size){
    if(text.length>=size){
        var out=text.substring(0,size);
        out+='...';
        return out;
    }
    return text;
}

function gup( name )
{
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( window.location.href );
    if( results == null )
    return "";
    else
    return results[1];
}

function nl2br_js(myString){
    return myString.replace( /\n/g, '<br />\n' );
}
/***************************************/
/*popup*/
/****************************************/
/**
*return the viewport of the window
*/
function viewport()
{
    var e = window
    , a = 'inner';
    if ( !( 'innerWidth' in window ) )
    {
    a = 'client';
    e = document.documentElement || document.body;
    }
    return { width : e[ a+'Width' ] , height : e[ a+'Height' ] }
}
/**
*togles
*/
function toggle(div_id) {
    var el=$(div_id);

    if ( el.getStyle('display') == 'none' ) {	el.setStyle({'display':'block'});}
    else {el.setStyle({'display':'none'});}
}
/**
* sets the blanket size
*/
function blanket_size(popUpDivVar) {
    if (typeof window.innerWidth != 'undefined') {
            viewportheight = window.innerHeight;
    } else {
            viewportheight = document.documentElement.clientHeight;
    }
    if((viewportheight > document.body.parentNode.scrollHeight) && (viewportheight > document.body.parentNode.clientHeight)) {
            blanket_height = viewportheight;
    } else {
            if (document.body.parentNode.clientHeight > document.body.parentNode.scrollHeight) {
                    blanket_height = document.body.parentNode.clientHeight;
            } else {
                    blanket_height = document.body.parentNode.scrollHeight;
            }
    }
    var blanket = document.getElementById('blanket');
    blanket.style.height = blanket_height + 'px'; 
    }
    function window_pos(popUpDivVar) {
    var win=viewport();
    var popUpDiv = $(popUpDivVar);
    var top=(win.height/2)-parseInt(popUpDiv.getStyle('height'))/2;
    var left=(win.width/2)-parseInt(popUpDiv.getStyle('width'))/2;

    popUpDiv.setStyle({'top':top + 'px'});
    popUpDiv.setStyle({'left':left + 'px'});
}
function popupPlaylist(event){
  $('selectPlaylist').artistID=this.artistID;
  $('selectPlaylist').artistName=this.artistName;
  $('selectPlaylist').albumID=this.albumID;
  if(this.albumName){
      $('selectPlaylist').albumName=this.albumName;
      $('selectPlaylist').trackID=this.trackID;
  }
  $('selectPlaylist').trackName=this.trackName;
  popup('selectPlaylist');
}
function popup(windowname) {
    blanket_size(windowname);
    window_pos(windowname);
    toggle('blanket');
    toggle(windowname);	
}
